<template>
  <header>
    <div class="header-content">
      <div class="logo" @click="goToHome">
        <img src="https://www.usian.cn/uploads/20250327/052111edb1cc05f9fd4ecebfe45264ec.png" alt="码镜空间logo">
        <span>码镜空间</span>
      </div>
      <nav class="nav-links">
        <a 
          v-for="category in navCategories" 
          :key="category.id"
          :class="{ active: currentCategory === category.id }"
          @click="handleNavClick(category)"
          href="#">
          {{ category.name }}
        </a>
      </nav>
      <div class="search-container">
        <input type="text" placeholder="请输入关键字...">
        <button><i class="fa fa-search"></i></button>
      </div>
      <div class="user-area">
        <div class="action-buttons">
          <button class="action-btn" @click="goToCart">
            <i class="fas fa-shopping-cart"></i>
            <span>购物车</span>
          </button>
          <button class="action-btn" @click="goToLearningCenter">
            <i class="fas fa-graduation-cap"></i>
            <span>学习中心</span>
          </button>
        </div>
        <template v-if="isLoggedIn">
          <div class="user-info">
            <router-link to="/user" class="username">{{ username }}</router-link>
            <button class="logout-btn" @click="handleLogout">
              <i class="fas fa-sign-out-alt"></i>
              <span>退出</span>
            </button>
          </div>
        </template>
        <template v-else>
          <router-link to="/login" class="login-btn">登录</router-link>
          <router-link to="/register" class="register-btn">注册</router-link>
        </template>
      </div>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const currentCategory = ref(null)

// 添加导航数据的响应式变量
const navCategories = ref([])

// 获取导航数据的方法
const fetchNavCategories = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:8000/api/nav/categories/')
    if (response.data.code === 1) {
      navCategories.value = response.data.data
    } else {
      console.error('获取导航数据失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取导航数据出错:', error)
  }
}

// 处理导航链接点击
const handleNavClick = (category) => {
  currentCategory.value = category.id
  if (category.external_link) {
    window.open(category.external_link, '_blank')
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchNavCategories()
  checkLoginStatus()
  
  // 监听登录状态变化
  window.addEventListener('storage', checkLoginStatus)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('storage', checkLoginStatus)
})

const goToCart = () => {
  router.push('/cart')
}

const goToLearningCenter = () => {
  router.push('/user')
}

const goToLogin = () => {
  router.push('/login')
}

const goToRegister = () => {
  router.push('/register')
}

const goToHome = () => {
  router.push('/')
}

const isLoggedIn = ref(false)
const username = ref('')

// 检查登录状态
const checkLoginStatus = () => {
  // 优先检查 sessionStorage
  let storedUsername = sessionStorage.getItem('username')
  let token = sessionStorage.getItem('token')
  
  // 如果 sessionStorage 中没有，则检查 localStorage
  if (!storedUsername || !token) {
    storedUsername = localStorage.getItem('username')
    token = localStorage.getItem('token')
  }
  
  if (storedUsername && token) {
    isLoggedIn.value = true
    username.value = storedUsername
  } else {
    isLoggedIn.value = false
    username.value = ''
  }
}

// 处理退出登录
const handleLogout = () => {
  // 清除 sessionStorage 中的数据
  sessionStorage.removeItem('token')
  sessionStorage.removeItem('userId')
  sessionStorage.removeItem('username')
  
  // 清除 localStorage 中的数据
  localStorage.removeItem('token')
  localStorage.removeItem('userId')
  localStorage.removeItem('username')
  localStorage.removeItem('loginInfo')
  
  // 更新登录状态
  isLoggedIn.value = false
  username.value = ''
  
  // 跳转到首页
  router.push('/')
}
</script>

<style scoped>
header {
  background: #ffffff;
  border-bottom: 1px solid #e0e0e0;
  padding: 12px 0;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  display: flex;
  align-items: center;
}

.logo img {
  height: 40px;
  margin-right: 8px;
}

.logo span {
  font-size: 14px;
  color: #666666;
}

.nav-links {
  display: flex;
  align-items: center;
  gap: 30px;
}

.nav-links a {
  text-decoration: none;
  color: #333;
  font-size: 16px;
  position: relative;
  padding: 4px 0;
}

.nav-links a:hover,
.nav-links a.active {
  color: #ff6b00;
}

.nav-links a::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 2px;
  background: #ff6b00;
  transition: all 0.3s;
  transform: translateX(-50%);
}

.nav-links a:hover::after,
.nav-links a.active::after {
  width: 100%;
}

.search-container {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 24px;
  overflow: hidden;
}

.search-container input {
  border: none;
  padding: 10px 18px;
  outline: none;
  width: 300px;
  font-size: 14px;
  background: transparent;
}

.search-container button {
  border: none;
  background: transparent;
  padding: 10px;
  cursor: pointer;
}

.user-area {
  display: flex;
  align-items: center;
  gap: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.username {
  color: #333;
  font-size: 14px;
  text-decoration: none;
}

.username:hover {
  color: #ff9900;
}

.logout-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border: none;
  background: transparent;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.logout-btn:hover {
  color: #ff4d4f;
}

.logout-btn i {
  font-size: 14px;
}

.login-btn,
.register-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  text-decoration: none;
  transition: all 0.3s;
}

.login-btn {
  color: #666;
}

.login-btn:hover {
  color: #ff9900;
}

.register-btn {
  background: #ff9900;
  color: white;
}

.register-btn:hover {
  background: #ff8800;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-right: 20px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border: none;
  background: transparent;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  color: #ff9900;
}

.action-btn i {
  font-size: 16px;
}
</style> 